package com.appspot.newsographer.server.jdo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.repackaged.com.google.common.base.Hash;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable;
import com.appspot.newsographer.client.GuardianService;

public class GuardianServiceImpl extends RemoteServiceServlet implements 
	GuardianService{

	public HashMap<String, ArrayList<String>> searchGuardian(String searchString, String startDate, String endDate) {
		StringBuilder json = new StringBuilder();
		HashMap<String, ArrayList<String>> info = new HashMap<String, ArrayList<String>>();
		try
		{
			String guardianUrl = "http://content.guardianapis.com/search?";
			String queryParams = "q=" + searchString + "&page=1&page-size=20&order-by=newest&format=json&api-key=q6pyv2xwcmjg4v85sdz7caz4&show-tags=keyword&from-date=" + startDate + "&to-date=" + endDate;
			URL url = new URL(guardianUrl+queryParams);
			URLConnection urlc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
			String inputLine;
	        while ((inputLine = in.readLine()) != null){
	            json.append(inputLine.trim());
	        }
	        in.close();
	        JSONArray obj;
	        trymm
	        {
				obj = new JSONObject(json.toString()).getJSONObject("response").getJSONArray("results");
				
				for(int i = 0; i < obj.length(); i++)
		        {
					try
					{
						ArrayList<String> tagArr = new ArrayList<String>(); 
						JSONObject rec = obj.getJSONObject(i);
						JSONArray tags = rec.getJSONArray("tags");
						tagArr.add(rec.getString("webUrl"));
						for(int j = 0; j < tags.length(); j++)
						{
							JSONObject tag = tags.getJSONObject(j);
							tagArr.add(tag.getString("webTitle"));
						}
						info.put(rec.getString("webTitle"), tagArr);
					}
					catch (JSONException ex) {
						ex.printStackTrace();
					}
		        }
	        }
	        catch (JSONException ex) {
				ex.printStackTrace();
			}
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		return info;
	}
}
